var http = require("http"),
  browserify = require("browserify"),
  literalify = require("literalify"),
  fs = require("fs"),
  React = require("react"),
  ReactDOMServer = require("react-dom/server");

// export default
import App from "./app";

http
  .createServer(function(req, res) {
    if (req.url == "/") {
      res.setHeader("Content-Type", "text/html");
      var props = {
        items: ["Item 0", "Item 1"]
      };
      var html = ReactDOMServer.renderToStaticMarkup(
        <body>
          <div
            id="content"
            dangerouslySetInnerHTML={{
              __html: ReactDOMServer.renderToString(<App items={props.items} />)
            }}
          />

          <script
            dangerouslySetInnerHTML={{
              __html: "var APP_PROPS = " + JSON.stringify(props) + ";"
            }}
          />
          <script src="/react.production.min.js" />
          <script src="/react-dom.production.min.js" />
          <script src="/bundle.js" />
        </body>
      );
      res.end(html);
    } else if (req.url == "/bundle.js") {
      res.setHeader("Content-Type", "text/javascript");
      browserify()
        .add("./dest/browser.js")
        .transform(
          literalify.configure({
            "react": "window.React",
            "react-dom": "window.ReactDOM"
          })
        )
        .bundle()
        .pipe(res);
    } else if (
      req.url == "/react.production.min.js" ||
      req.url == "/react-dom.production.min.js"
    ) {
      res.setHeader("Content-Type", "text/javascript");
      //创建只读流用于返回
      var stream = fs.createReadStream("./lib" + req.url, {
        flags: "r",
        encoding: null
      });
      stream.on("error", () => {
        res.writeHead(404, { "Content-Type": "text/html" });
        res.end("<h1>404 Read File Error</h1>");
      });
      //连接文件流和http返回流的管道,用于返回实际Web内容
      stream.pipe(res);
    } else {
      res.statusCode = 404;
      res.end();
    }
  })
  .listen(3000, function(err) {
    if (err) throw err;
    console.log("Listening on 3000...");
  });
